package com.youlu.campus.service.organizer.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.base.exception.BusinessException;

import com.youlu.campus.common.utils.TimeUtils;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.req.ActivityOrganizeBatchVerify;
import com.youlu.campus.entity.VO.req.ActivityOrganizerBaseInfo;
import com.youlu.campus.entity.VO.req.ActivityOrganizerQueryVO;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.entity.system.UserDataPermission;
import com.youlu.campus.service.activity.ActivityTaskService;
import com.youlu.campus.service.activity.UserActivityTaskInfoService;
import com.youlu.campus.service.file.FileExportTaskService;
import com.youlu.campus.service.file.FileService;
import com.youlu.campus.service.organizer.ActivityOrganizerInfoService;
import com.youlu.campus.service.ranking.OrganizerRankingService;
import com.youlu.campus.service.system.UserDataPermissionService;
import com.youlu.campus.service.university.UniversityInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

@Slf4j
@Service
public class ActivityOrganizerInfoServiceImpl implements ActivityOrganizerInfoService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private FileExportTaskService fileExportTaskService;
    @Autowired
    private FileService fileService;
    @Autowired
    private UniversityInfoService universityInfoService;
    @Autowired
    private UserActivityTaskInfoService userActivityTaskInfoService;
    @Autowired
    private ActivityTaskService activityTaskService;
    @Lazy
    @Autowired
    private UserDataPermissionService userDataPermissionService;
    @Autowired
    @Lazy
    private OrganizerRankingService organizerRankingService;
    @Value("${sys.fileExportPath:/data/file/campus-admin/}")
    private String fileExportPath;

    @Override
    public Page<ActivityOrganizerInfo> list(ActivityOrganizerQueryVO req) {
        log.info(":>>> 开始获取承办单位信息:{}", JSON.toJSONString(req));
        if (Objects.isNull(req) || Objects.isNull(req.getPage()) || Objects.isNull(req.getPageSize())) {
            log.error(":>>> 承办单位参数错误");
            throw new BusinessException("承办单位参数错误");
        }
        Query query = new Query();
        if (StringUtils.isNotBlank(req.getName())) {
            Pattern pattern = Pattern.compile("^.*" + req.getName() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("name").regex(pattern));
        }
        if (StringUtils.isNotBlank(req.getOrgName())) {
            Pattern pattern = Pattern.compile("^.*" + req.getOrgName() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("orgName").regex(pattern));
        }
        if (StringUtils.isNotBlank(req.getMobile())) {
            query.addCriteria(Criteria.where("mobile").is(req.getMobile()));
        }
        if (StringUtils.isNotBlank(req.getUniversityId())) {
            query.addCriteria(Criteria.where("universityId").is(req.getUniversityId()));
        }
        UserDataPermission userDataPermission = null;
        List<String> activityIds = new ArrayList<>();
        if (StringUtils.isNotBlank(req.getUserId())) {
            UserDataPermission reqP = new UserDataPermission();
            reqP.setUserId(req.getUserId());
            List<UserDataPermission> datas = userDataPermissionService.list(reqP);
            if (!CollectionUtils.isEmpty(datas) && !CollectionUtils.isEmpty(datas.get(0).getActivityId())) {
                userDataPermission = datas.get(0);
                log.info(":>>> 用户:{} 的数据权限权限配置:{}", req.getUserId(), JSON.toJSON(userDataPermission.getActivityId()));
                activityIds = datas.get(0).getActivityId();
            }
        }
        if (StringUtils.isNotBlank(req.getActivityId())) {
            query.addCriteria(Criteria.where("activityId").is(req.getActivityId()));
        } else {
            if (!CollectionUtils.isEmpty(activityIds)) {
                query.addCriteria(Criteria.where("activityId").in(activityIds));
            }
        }
        // H5端只显示审核通过的承办单位
        if ("h5-api".equals(req.getBizFrom())) {
            query.addCriteria(Criteria.where("status").is(1));
        } else {
            if (Objects.nonNull(req.getStatus())) {
                query.addCriteria(Criteria.where("status").is(req.getStatus()));
            }
        }
        if (StringUtils.isNotBlank(req.getUniversityName())) {
            Pattern pattern = Pattern.compile("^.*" + req.getUniversityName() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("universityName").regex(pattern));
        }
        long count = mongoTemplate.count(query, ActivityOrganizerInfo.class);
        PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<ActivityOrganizerInfo> infos = mongoTemplate.find(query.with(pageRequest), ActivityOrganizerInfo.class);
        for (ActivityOrganizerInfo activityOrganizerInfo : infos) {
            Query queryA = new Query().addCriteria(Criteria.where("id").is(activityOrganizerInfo.getActivityId()));
            ActivityInfo activityInfo = mongoTemplate.findOne(queryA, ActivityInfo.class);
            if (Objects.nonNull(activityInfo)) {
                activityOrganizerInfo.setActivityName(activityInfo.getName());
            }
        }
        return PageableExecutionUtils.getPage(infos, pageRequest, () -> count);
    }

    @Override
    public boolean create(ActivityOrganizerInfo req) {
        log.info(":>>> 开始新增承办单位:{}", JSON.toJSONString(req));
        if (Objects.isNull(req) || StringUtils.isBlank(req.getActivityId()) || StringUtils.isBlank(req.getUniversityId()) ||
                StringUtils.isBlank(req.getOwnerUserId()) || StringUtils.isBlank(req.getOrgName())) {
            log.error(":>>> 新增承办单位参数错误:活动ID、大学ID为空、承办人信息为空");
            throw new BusinessException("新增承办单位参数错误");
        }
        Query query = new Query().addCriteria(Criteria.where("universityId").is(req.getUniversityId()).and("orgName").is(req.getOrgName()).and("activityId").is(req.getActivityId()));
        boolean exist = mongoTemplate.exists(query, ActivityOrganizerInfo.class);
        if (exist) {
            log.error(":>>> 大学:{},单位:{} 已经存在", req.getUniversityId(), req.getOrgName());
            throw new BusinessException("承办单位已经存在");
        }
        Query queryU = new Query().addCriteria(Criteria.where("id").is(req.getUniversityId()));
        UniversityInfo info = mongoTemplate.findOne(queryU, UniversityInfo.class);
        if (Objects.nonNull(info)) {
            req.setUniversityName(info.getName());
        }
        req.setCreatedTime(new Date());
        req.setId(null);
        mongoTemplate.insert(req);
        ActivityTaskInfo taskInfo = activityTaskService.find(req.getActivityId(), TaskBizType.ORGANIZER);
        UserActivityTaskInfo userActivityTaskInfo = new UserActivityTaskInfo();
        userActivityTaskInfo.setActivityId(req.getActivityId());
        userActivityTaskInfo.setUserId(req.getOwnerUserId());
        userActivityTaskInfo.setTaskId(taskInfo.getId());
        userActivityTaskInfo.setDoType("all");
        userActivityTaskInfo.setStatus(1);
        userActivityTaskInfo.setTaskBizType(TaskBizType.ORGANIZER);
        userActivityTaskInfoService.create(userActivityTaskInfo);
        return true;
    }

    @Override
    public boolean update(ActivityOrganizerInfo req) {
        log.info(":>>> 开始修改承办单位:{}", JSON.toJSONString(req));
        if (Objects.isNull(req) || StringUtils.isBlank(req.getId())) {
            log.error(":>>> 修改承办单位参数错误:ID为空");
            throw new BusinessException("修改承办单位参数错误:ID为空");
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(req.getId()));
        ActivityOrganizerInfo exist = mongoTemplate.findOne(query, ActivityOrganizerInfo.class);
        if (Objects.isNull(exist)) {
            log.error(":>>> 承办单位不存在:{}", req.getId());
            throw new BusinessException("承办单位不存在");
        }
        Update update = new Update();
        Update updateOrg = new Update();
        boolean updateOrgFlag = false;
        if (StringUtils.isNotBlank(req.getUniversityId())) {
            update.set("universityId", req.getUniversityId());
            UniversityInfo universityInfo = universityInfoService.findOne(req.getUniversityId());
            if (Objects.nonNull(universityInfo)) {
                update.set("universityName", universityInfo.getName());
            }
        }
        if (StringUtils.isNotBlank(req.getDetail())) {
            update.set("detail", req.getDetail());
        }
        if (StringUtils.isNotBlank(req.getLogoImageUrl())) {
            update.set("logoImageUrl", req.getLogoImageUrl());
            updateOrg.set("imageUrl", req.getLogoImageUrl());
            updateOrgFlag = true;
        }
        if (StringUtils.isNotBlank(req.getMobile())) {
            update.set("mobile", req.getMobile());
        }
        if (StringUtils.isNotBlank(req.getName())) {
            update.set("name", req.getName());
        }
        if (StringUtils.isNotBlank(req.getOrgName())) {
            update.set("orgName", req.getOrgName());
            updateOrg.set("name", req.getName());
            updateOrgFlag = true;
        }
        if (StringUtils.isNotBlank(req.getPosition())) {
            update.set("position", req.getPosition());
        }
        if (StringUtils.isNotBlank(req.getQq())) {
            update.set("qq", req.getQq());
        }
        if (StringUtils.isNotBlank(req.getComment())) {
            update.set("comment", req.getComment());
        }
        if (Objects.nonNull(req.getStatus())) {
            update.set("status", req.getStatus());
        }
        update.set("updatedTime", new Date());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, ActivityOrganizerInfo.class);
        log.info(":>>> 更新承办组织结果:{}", updateResult.getModifiedCount() > 0 ? true : false);
        if (Objects.nonNull(req.getStatus()) && req.getStatus().intValue() == 1) {
            Query queryTask = new Query().addCriteria(Criteria.where("activityId").is(exist.getActivityId()).and("taskBizType").is(TaskBizType.ORGANIZER));
            ActivityTaskInfo taskInfo = mongoTemplate.findOne(queryTask, ActivityTaskInfo.class);
            if (Objects.nonNull(taskInfo)) {
                Query query1 = new Query().addCriteria(Criteria.where("activityId").is(exist.getActivityId()).and("taskId").is(taskInfo.getId()).and("organizerId").is(exist.getId()));
                boolean existOrg = mongoTemplate.exists(query1, OrganizerRankingList.class);
                if (!existOrg) {
                    log.info(":>>> 承办单位未在榜单中:{}", exist.getId());
                    OrganizerRankingList ranking = new OrganizerRankingList();
                    ranking.setActivityId(exist.getActivityId());
                    ranking.setUserId(exist.getOwnerUserId());
                    ranking.setTaskId(taskInfo.getId());
                    ranking.setTaskBizType(taskInfo.getTaskBizType());
                    ranking.setCreatedTime(new Date());
                    ranking.setImageUrl(exist.getLogoImageUrl());
                    ranking.setName(exist.getOrgName());
                    ranking.setQuantity(1.0D);
                    ranking.setUniversityId(exist.getUniversityId());
                    ranking.setUniversityName(exist.getUniversityName());
                    ranking.setOrganizerId(exist.getId());
                    mongoTemplate.insert(ranking);
                    log.info(":>>> 承办单位未在榜单中,新增:{}", ranking);
                } else {
                    log.info(":>>> 承办单位在榜单中,不新增:{},活动:{}", exist.getId(), exist.getActivityId());
                    if (updateOrgFlag) {
                        UpdateResult updateResult1 = mongoTemplate.updateMulti(query1, updateOrg, OrganizerRankingList.class);
                        log.info(":>>> 更新活动:{} 承办单位:{},数量:{}", exist.getActivityId(), updateResult1.getModifiedCount());
                    }

                }
            }
        }
        boolean resut = updateResult.getModifiedCount() > 0 ? true : false;
        if (resut) {
            UserActivityTaskInfo userActivityTaskInfo = userActivityTaskInfoService.find(exist.getOwnerUserId(),
                    exist.getActivityId(), TaskBizType.ORGANIZER);
            if(userActivityTaskInfo != null){
                UserActivityTaskInfo updater = new UserActivityTaskInfo();
                updater.setId(userActivityTaskInfo.getId());
                updater.setUpdatedTime(new Date());
                //  * 状态,0:待审核,1:审核通过,2:审核不通过，3:未报名
                if (req.getStatus().intValue() == 1) {
                    updater.setStatus(2);
                } else {
                    updater.setStatus(1);
                }
                userActivityTaskInfoService.update(updater);
            }
        }
        if (Objects.nonNull(req.getStatus())) {
            organizerRankingService.updateOrganizerRankingStatus(exist.getId(), exist.getActivityId(), req.getStatus());

        }
        return resut;
    }

    @Override
    public boolean batchVerify(ActivityOrganizeBatchVerify req) {
        Query query = new Query().addCriteria(Criteria.where("id").in(req.getIdList()));
        List<ActivityOrganizerInfo> list  = mongoTemplate.find(query, ActivityOrganizerInfo.class);
        if(CollectionUtils.isEmpty(list)){
            throw new BusinessException("申请记录Id不能为空");
        }
        if(req.getStatus() == null){
            throw new BusinessException("状态不能为空");
        }
        for (ActivityOrganizerInfo exist : list) {
            Query q = new Query().addCriteria(Criteria.where("id").is(exist.getId()));
            Update u = new Update();
            u.set("updatedTime", new Date());
            u.set("status",req.getStatus());
            UpdateResult updateResult = mongoTemplate.updateFirst(q, u, ActivityOrganizerInfo.class);
            if(updateResult.getModifiedCount()<=0){
                continue;
            }
            if(Integer.valueOf(1).equals(req.getStatus())){
                // 添加排行信息
                addRankInfo(exist);
            }
            // 更新用户申请状态
            updateUserApplyInfo(exist,req.getStatus());
            // 更新排行数据状态
            organizerRankingService.updateOrganizerRankingStatus(exist.getId(), exist.getActivityId(), req.getStatus());
        }
        return true;
    }

    public void updateUserApplyInfo(ActivityOrganizerInfo organizerInfo,Integer status){
        // 更新用户审核记录
        UserActivityTaskInfo userActivityTaskInfo = userActivityTaskInfoService.find(organizerInfo.getOwnerUserId(), organizerInfo.getActivityId(), TaskBizType.ORGANIZER);
        if(userActivityTaskInfo != null){
            UserActivityTaskInfo updater = new UserActivityTaskInfo();
            updater.setId(userActivityTaskInfo.getId());
            updater.setUpdatedTime(new Date());
            //  * 状态,0:待审核,1:审核通过,2:审核不通过，3:未报名
            if (status == 1) {
                updater.setStatus(2);
            } else {
                updater.setStatus(1);
            }
            userActivityTaskInfoService.update(updater);
        }
    }

    public void addRankInfo(ActivityOrganizerInfo organizerInfo){
        Query queryTask = new Query().addCriteria(Criteria.where("activityId").is(organizerInfo.getActivityId()).and("taskBizType").is(TaskBizType.ORGANIZER));
        ActivityTaskInfo taskInfo = mongoTemplate.findOne(queryTask, ActivityTaskInfo.class);
        if(taskInfo == null){
            return;
        }
        Query query1 = new Query().addCriteria(Criteria.where("activityId").is(organizerInfo.getActivityId()).and("taskId").is(taskInfo.getId()).and("organizerId").is(organizerInfo.getId()));
        boolean existOrg = mongoTemplate.exists(query1, OrganizerRankingList.class);
        if (existOrg) {
            log.info("addRankInfo,org rank exist,aid:{},taskId:{},oid:{}",organizerInfo.getActivityId(),taskInfo.getId(),organizerInfo.getId());
            return;
        }
        OrganizerRankingList ranking = new OrganizerRankingList();
        ranking.setActivityId(organizerInfo.getActivityId());
        ranking.setUserId(organizerInfo.getOwnerUserId());
        ranking.setTaskId(taskInfo.getId());
        ranking.setTaskBizType(taskInfo.getTaskBizType());
        ranking.setCreatedTime(new Date());
        ranking.setImageUrl(organizerInfo.getLogoImageUrl());
        ranking.setName(organizerInfo.getOrgName());
        ranking.setQuantity(1.0D);
        ranking.setUniversityId(organizerInfo.getUniversityId());
        ranking.setUniversityName(organizerInfo.getUniversityName());
        ranking.setOrganizerId(organizerInfo.getId());
        mongoTemplate.insert(ranking);
    }

    @Override
    public ActivityOrganizerInfo findOne(String id) {
        log.info(":>>> 开始查找活动承办单位信息:{}", id);
        if (StringUtils.isBlank(id)) {
            log.error(":>>> 获取承办单位信息错误:参数为空");
            throw new BusinessException("参数为空");
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        ActivityOrganizerInfo activityOrganizerInfo = mongoTemplate.findOne(query, ActivityOrganizerInfo.class);
        log.info(":>>> 活动承办单位信息为:{}", JSON.toJSONString(activityOrganizerInfo));
        return activityOrganizerInfo;
    }

    @Override
    public ActivityOrganizerBaseInfo getBaseInfo(String activityId, UserPO userPO) {
        log.info(":>>> 开始获取承办单位基础信息:{},{}", activityId, JSON.toJSONString(userPO));
        if (StringUtils.isBlank(activityId) || Objects.isNull(userPO)) {
            log.error(":>>> 获取承办单位基础信息错误:参数为空");
            throw new BusinessException("参数为空");
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(activityId));
        ActivityInfo activityInfo = mongoTemplate.findOne(query, ActivityInfo.class);
        if (Objects.isNull(activityId)) {
            log.error(":>>> 活动不存在");
            throw new BusinessException("活动不存在");
        }
        ActivityOrganizerBaseInfo res = new ActivityOrganizerBaseInfo();
        res.setDetail(activityInfo.getOrganizerDetail());
        res.setName(userPO.getName());
        res.setMobile(userPO.getMobile());
        res.setUniversityId(userPO.getUniversityId());
        res.setQq(userPO.getQqNumber());
        if (StringUtils.isNotBlank(userPO.getUniversityId())) {
            Query queryU = new Query().addCriteria(Criteria.where("id").is(userPO.getUniversityId()));
            UniversityInfo info = mongoTemplate.findOne(queryU, UniversityInfo.class);
            if (Objects.nonNull(info)) {
                res.setUniversityName(info.getName());
            }
        }
        return res;
    }

    @Override
    public ActivityOrganizerInfo find(String activityId, String userId) {
        log.info(":>>> 开始查找承办单位:{},{}", activityId, userId);
        if (StringUtils.isBlank(activityId) || StringUtils.isBlank(userId)) {
            log.error(":>>> 承办单位基础信息错误:参数为空");
            throw new BusinessException("参数为空");
        }
//        Query query = new Query().addCriteria(Criteria.where("activityId").is(activityId).and("ownerUserId").is(userId));
        Query query = new Query().addCriteria(Criteria.where("ownerUserId").is(userId).and("activityId").is(activityId));
        ActivityOrganizerInfo res = mongoTemplate.findOne(query, ActivityOrganizerInfo.class);
        log.info(":>>> 承担单位信息:{}", JSON.toJSONString(res));
        if (Objects.isNull(res)) {
            Query query1 = new Query().addCriteria(Criteria.where("userId").is(userId).and("activityId").is(activityId));
            UserParticipateActivityInfo participateActivityInfo = mongoTemplate.findOne(query1, UserParticipateActivityInfo.class);
            if (Objects.nonNull(participateActivityInfo)) {
                res = new ActivityOrganizerInfo();
                res.setName(participateActivityInfo.getName());
                res.setMobile(participateActivityInfo.getMobile());
                res.setUniversityId(participateActivityInfo.getUniversityId());
                res.setUniversityName(participateActivityInfo.getUniversityName());
                res.setQq(participateActivityInfo.getQq());
                return res;
            }

        }
        return res;
    }

    @Override
    public boolean joinOrganizer(String tenantId, String userId, String organizerId) {
        return false;
    }

    @Override
    public String getOrganizerId(String tenantId, String userId) {
        if (StringUtils.isBlank(userId)) {
            log.error(":>>> userId为空");
            return null;
        }
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId));
        OrganizerUserInfo o = mongoTemplate.findOne(query, OrganizerUserInfo.class);
        if (Objects.isNull(o)) {
            log.error(":>>> userId:{} 为加入申办机构", userId);
            return null;
        }
        log.info(":>>> 用户:{} 的申办机构为:{}", userId, o.getOrganizerId());
        return o.getOrganizerId();
    }

    @Override
    public boolean export(String activityId, String taskId, String optName, String userId) {
        log.info(":>>> 开始导出承办单位");
        Query query = new Query().addCriteria(Criteria.where("activityId").is(activityId));
        List<ActivityOrganizerInfo> datas = mongoTemplate.find(query, ActivityOrganizerInfo.class);
        if (CollectionUtils.isEmpty(datas)) {
            return true;
        }
        log.info(":>>> 订单总量:{}", datas.size());
        FileExportTask fileExportTask = new FileExportTask();
        fileExportTask.setToken(optName);
        fileExportTask.setBizType("2");
        fileExportTask.setStatus(0);
        fileExportTask.setOptUser(optName);
        fileExportTask.setOptUserId(userId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(new Date());
        String fileName = "活动承办单位信息-" + datas.size() + "条-" + dateStr;
        String f = fileName + System.currentTimeMillis() + ".xlsx";
        fileExportTask.setFileName(f);
        fileExportTask.setNum(datas.size());
        fileExportTask.setDesc("活动承办单位信息");
        String re = fileExportTaskService.create(fileExportTask);
        this.exportOrgInfo(query, f, re);
        return true;


    }

    @Override
    public HashMap<String, ActivityOrganizerInfo> findByIds(List<String> orgIds) {
        HashMap<String, ActivityOrganizerInfo> res = new HashMap<>();
        Query query = new Query().addCriteria(Criteria.where("id").in(orgIds));
        List<ActivityOrganizerInfo> orgs = mongoTemplate.find(query, ActivityOrganizerInfo.class);
        if (CollectionUtils.isEmpty(orgs)) {
            return res;
        }
        for (ActivityOrganizerInfo a : orgs) {
            res.put(a.getId(), a);

        }
        return res;
    }

    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            fileName = new String(fileName.getBytes());
            response.reset();
            response.setContentType("application/msexcel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            log.error(":>>> setResponseHeader error:{}", ex);
        }
    }

    private void setOrgUserExcelTitle(HSSFWorkbook workbook, HSSFSheet sheet) {
        HSSFRow row = sheet.createRow(0);
        //设置列宽，setColumnWidth的第二个参数要乘以256，这个参数的单位是1/256个字符宽度
        sheet.setColumnWidth(0, 10 * 256);
        sheet.setColumnWidth(1, 20 * 256);
        sheet.setColumnWidth(2, 20 * 256);
        sheet.setColumnWidth(3, 100 * 256);

        //设置为居中加粗
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        style.setFont(font);

        HSSFCell cell;
        cell = row.createCell(0);
        cell.setCellValue("大学");
        cell.setCellStyle(style);

        cell = row.createCell(1);
        cell.setCellValue("姓名");
        cell.setCellStyle(style);

        cell = row.createCell(2);
        cell.setCellValue("手机号");
        cell.setCellStyle(style);

        cell = row.createCell(3);
        cell.setCellValue("申请时间");
        cell.setCellStyle(style);


        cell = row.createCell(4);
        cell.setCellValue("邀请人数");
        cell.setCellStyle(style);

        cell = row.createCell(5);
        cell.setCellValue("QQ");
        cell.setCellStyle(style);

        cell = row.createCell(6);
        cell.setCellValue("所在学校报名人数");
        cell.setCellStyle(style);

        cell = row.createCell(7);
        cell.setCellValue("机构名字");
        cell.setCellStyle(style);


    }

        private void exportOrgInfo(Query query, String f, String exportTaskId) {

        int counter = 0;
        HSSFWorkbook workbook = new HSSFWorkbook();
        HashMap<String, UniversityInfo> universityInfoHashMap = new HashMap<>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            int rowNum = 1;
            int sheetNum = 1;
            //创建一个Excel表单,参数为sheet的名字
            HSSFSheet sheet = workbook.createSheet("sheet" + "-" + sheetNum);
            setOrgUserExcelTitle(workbook, sheet);
            //创建表头
            List<ActivityOrganizerInfo> datas = mongoTemplate.find(query, ActivityOrganizerInfo.class);
            for (ActivityOrganizerInfo up : datas) {
                UniversityInfo universityInfo = null;
                if (StringUtils.isNotBlank(up.getUniversityId())) {
                    if (universityInfoHashMap.containsKey(up.getUniversityId())) {
                        universityInfo = universityInfoHashMap.get(up.getUniversityId());
                    } else {
                        Query query1 = new Query().addCriteria(Criteria.where("id").is(up.getUniversityId()));
                        universityInfo = mongoTemplate.findOne(query1, UniversityInfo.class);
                        universityInfoHashMap.put(up.getUniversityId(), universityInfo);
                    }
                }
                log.info(":>>> 导出行数:{}", counter);
                if (counter != 0 && counter % 60000 == 0) {
                    //超过60000就自动创建一个sheet
                    sheetNum++;
                    sheet = workbook.createSheet("sheet-" + sheetNum);
                    setOrgUserExcelTitle(workbook, sheet);
                    //创建表头
                    //新增数据行，并且设置单元格数据
                    rowNum = 1;
                    sheetNum++;
                    log.info(":>>> 操作60000行,创建新sheet");
                }
                HSSFRow row = sheet.createRow(rowNum);
                if (Objects.nonNull(universityInfo)) {
                    if (StringUtils.isNotBlank(universityInfo.getName())) {
                        row.createCell(0).setCellValue(universityInfo.getName());
                    }
                    if (StringUtils.isNotBlank(universityInfo.getCity())) {
                        row.createCell(8).setCellValue(universityInfo.getCity());
                    }
                    if (StringUtils.isNotBlank(universityInfo.getType())) {
                        row.createCell(9).setCellValue(universityInfo.getType());
                    }

                }
                if (StringUtils.isNotBlank(up.getName())) {
                    row.createCell(1).setCellValue(up.getName());
                }
                if (StringUtils.isNotBlank(up.getMobile())) {
                    row.createCell(2).setCellValue(up.getMobile());
                }
                if (Objects.nonNull(up.getCreatedTime())) {
                    String dateNowStr = TimeUtils.parse(up.getCreatedTime(), "yyyy-MM-dd HH:mm:ss");
                    row.createCell(3).setCellValue(dateNowStr);
                }
                if (StringUtils.isNotBlank(up.getQq())) {
                    row.createCell(5).setCellValue(up.getQq());
                }
                if (StringUtils.isNotBlank(up.getOrgName())) {
                    row.createCell(6).setCellValue(up.getOrgName());
                }
                Query query1 = new Query().addCriteria(Criteria.where("activityId").is(up.getActivityId()).and("taskBizType").is(TaskBizType.ORGANIZER));

                ActivityTaskInfo taskInfo = mongoTemplate.findOne(query1, ActivityTaskInfo.class);

                Double q = getOrgQ(up.getActivityId(), taskInfo.getId(), up.getId());
                if (Objects.nonNull(q)) {
                    row.createCell(4).setCellValue(q);
                }
                rowNum++;
                counter++;
            }

            //将excel写入到输出流中
            log.info(":>>> flush:{} 行", rowNum);
            OutputStream outputStream = new FileOutputStream(fileExportPath + f);
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            log.info(":>>> 写文件到本地然后读:{}", f);
            File file = new File(fileExportPath + f);
            InputStream in = new FileInputStream(file);
            String url = fileService.uploadFile(in, f);
            Query queryTask = new Query().addCriteria(Criteria.where("id").is(exportTaskId));
            Update update = new Update();
            update.set("url", url);
            update.set("status", 1);
            update.set("updatedTime", new Date());
            UpdateResult updateResult = mongoTemplate.updateFirst(queryTask, update, FileExportTask.class);
            log.info(":>>> 更新任务:{},状态:{}", exportTaskId, updateResult.getModifiedCount() > 0 ? true : false);
            in.close();
            log.info(":>>> 所有活动参与员导出,关闭文件流");
        } catch (Exception e) {
            log.error(":>>> 所有活动参与员导出错误:{}", e);
        }
    }

    private Double getOrgQ(String activityId, String taskId, String organizerId) {
        Query queryU = new Query();
        queryU.addCriteria(Criteria.where("organizerId").is(organizerId).and("taskId").is(taskId).and("activityId"
        ).is(activityId));
        OrganizerRankingList day = mongoTemplate.findOne(queryU, OrganizerRankingList.class);
        if (Objects.isNull(day)) {
            return 0.0D;
        } else {
            return day.getQuantity();
        }
    }
}
